package com.scalar.chiptrack.adaptor.unisem;

import com.scalar.chiptrack.jobs.JobHandler;
import com.scalar.chiptrack.adaptor.AdaptorConstants;
import com.scalar.chiptrack.adaptor.AdaptorUtils;
import com.scalar.chiptrack.adaptor.dao.AdaptorRunInfo;
import com.scalar.chiptrack.utils.Logger;
import com.scalar.chiptrack.utils.StringUtils;
import com.scalar.chiptrack.utils.DateUtil;
import com.scalar.chiptrack.users.VendorAdaptor;
import com.scalar.chiptrack.users.dao.AdaptorSetUpDAO;
import com.scalar.ScalarException;

import java.io.BufferedInputStream;

import HTTPClient.HTTPConnection;
import HTTPClient.HTTPResponse;
import HTTPClient.CookieModule;
import HTTPClient.NVPair;


/**
 * Created by IntelliJ IDEA.
 * User: munugoti
 * Date: 8 Oct, 2009
 * Time: 1:29:00 PM
 * To change this template use File | Settings | File Templates.
 */
public class UNISEMAdaptor extends JobHandler implements AdaptorConstants
{
    private static final String PROTOCOL_HTTP           = "http";
    private static final String HOST                    = "ipohweb.unisemgroup.com";
    private static final String POST_LOGIN_URL          = "/UnisemServlet?target=access&cmd=LOGIN";
    private static final String LOG_OUT                 = "/UnisemServlet?target=access&cmd=LOGOUT";
    private static final int DEFAULT_PORT               = 80;

    public static final String FILE_NAME_WIP_STATUS     = "UNISEM_WIP_STATUS";
    public static final String ADAPTOR_NAME             = "UNISEM_WIP";

    private String m_dataOutputDir      = null;
    private Logger m_adaptorLogger      = null;
    private String m_username           = null;
    private String m_password           = null;
    private String m_customerName       = null;
    private int    m_adaptor_id     = -1;


    public UNISEMAdaptor() throws Exception
    {
        try
        {
            VendorAdaptor vendorAdaptor = AdaptorSetUpDAO.getVendorAdaptorDetailsByVendorNameAndLocation( VENDOR_NAME_UNISEM, LOCATION_TYPE_ASSEMBLY );

            if( vendorAdaptor == null )
            {
                log( "ERROR!! ERROR!! ERROR!! Exception while loading UNISEM Adaptor Username, Password details from database" );
                throw new ScalarException( "Exception while loading UNISEM Adaptor Username, Password details from database" );
            }

            m_username = vendorAdaptor.getUserId().trim();
            m_password = vendorAdaptor.getPassWord().trim();
            m_dataOutputDir = vendorAdaptor.getOutPutDirectory().trim();
            m_customerName = vendorAdaptor.getCustomerId().trim();//MSI
            if ( m_dataOutputDir != null )
            {
                if ( m_dataOutputDir.endsWith( "/" ) || m_dataOutputDir.endsWith( "\\" ) )
                {
                    m_dataOutputDir = m_dataOutputDir + m_username;
                }
                else
                {
                    m_dataOutputDir = m_dataOutputDir + "/" + m_username;
                }

                AdaptorUtils.makeAllAdaptorDirs( m_dataOutputDir );
                m_adaptorLogger = AdaptorUtils.getAdaptorLogger( m_dataOutputDir, VENDOR_NAME_UNISEM );
                AdaptorUtils.setLogger( m_adaptorLogger );
            }
        }
        catch ( Exception se )
        {
            log( "ERROR!! ERROR!! ERROR!! Exception while loading UNISEM Adaptor Username, Password details from database, Exception: " + se );
            throw new ScalarException( "Exception while loading UNISEM Adaptor Username, Password details from database" );
        }
    }

    public static void main( String[] args ) throws Exception
    {
        try
        {
            new UNISEMAdaptor().execute();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }

    public void execute() throws Exception
    {
        try
        {
            m_adaptor_id = AdaptorRunInfo.saveAdaptorLastUpdatedStatus( CONSTANT_ADAPTOR, ADAPTOR_NAME, CONSTANT_SUCCESS, -1);

            AdaptorUtils.printHeader(VENDOR_NAME_UNISEM, CONSTANT_ADAPTOR);

            AdaptorUtils.removeOldFiles(m_dataOutputDir, m_adaptorLogger);

            HTTPConnection connection = login( HOST, DEFAULT_PORT, m_username, m_password );

            if ( connection != null )
            {
                BufferedInputStream bfReader = null;

                //For DownLoading WipStatus Report
                HTTPResponse rsp = requestWipStatusReport( connection );

                if( rsp != null )
                {
                    bfReader = new BufferedInputStream( rsp.getInputStream()  );
                    if( bfReader != null )
                    {
                        System.out.println( "\tDownloading the Wip Status Sheet..." );
                        log( "\tDownloading the Wip Status Sheet..." );
                        AdaptorUtils.saveAsBinaryFile( bfReader, m_dataOutputDir, FILE_NAME_WIP_STATUS, FILE_EXTN_XLS,true );
                        if (m_adaptor_id > 0 )
                        {
                            AdaptorRunInfo.saveAdaptorFileInfo( m_adaptor_id , FILE_NAME_WIP_STATUS, FILE_EXTN_XLS, StringUtils.formatDateandTime(DateUtil.getFormattedTimeStamp() )) ;
                        }
                    }
                    else
                    {
                        log( "Could not save Lot Status Sheet from Buffer Reader" );
                        throw new ScalarException( "Could not save Wip Status Sheet from Buffer Reader" );
                    }
                }
                else
                {
                    log( "Could not create response object of Wip Status Sheet" );
                    throw new ScalarException( "Could not create response object of Wip Status Sheet" );
                }

                // Logging out from UNISEM WEB SITE
                logout( connection );
                bfReader = null;
            }
            else
            {
                log( "Could not able to get the Connection to web site" );
                throw new ScalarException( "Could not able to get the Connection to web site" );
            }
        }
        catch(Exception e)
        {
            AdaptorUtils.removeOldFiles(m_dataOutputDir, m_adaptorLogger);
            AdaptorRunInfo.updatedAdaptorStatus( CONSTANT_FAILURE, m_adaptor_id);
            System.out.println("Exception while trying to connect and read data from " + HOST +" site: " + e);
            log("Exception while trying to connect and read data from " + HOST +" site: " + e);
            e.printStackTrace();
            throw e;
        }
    }

    private HTTPConnection login( String host, int port, String username, String password ) throws Exception
    {
        byte[] data         = new byte[1024];
        HTTPResponse    rsp = null;

        HTTPConnection conn = new HTTPConnection( PROTOCOL_HTTP, host, port );
        CookieModule.setCookiePolicyHandler( null );
        HTTPConnection.addDefaultModule( CookieModule.class, -1 );

        NVPair defaultHeaders[] = new NVPair[ 8 ];
        defaultHeaders[ 0 ] = new NVPair( "Accept", "image/gif, image/x-xbitmap, image/jpeg, application/x-ms-application, application/vnd.ms-xpsdocument, application/xaml+xml, application/x-ms-xbap, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, image/pjpeg, */*" );
        defaultHeaders[ 1 ] = new NVPair( "Accept-Language", "en-us" );
        defaultHeaders[ 2 ] = new NVPair( "Content-Type", "application/x-www-form-urlencoded" );
        defaultHeaders[ 3 ] = new NVPair( "Proxy-Connection", "Keep-Alive" );
        defaultHeaders[ 4 ] = new NVPair( "User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; GTB6; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; InfoPath.2; .NET CLR 3.5.30729; .NET CLR 3.0.30729)" );
        defaultHeaders[ 5 ] = new NVPair( "Host", host );
        defaultHeaders[ 6 ] = new NVPair( "Pragma", "no-cache" );

        conn.setDefaultHeaders( defaultHeaders );

        rsp=conn.Get("/sign_in.html");
        /*while ( rsp.getInputStream().read( data ) != -1 )
        {
        	log( new String( data ) );
        }*/
        NVPair[] formData = new NVPair[ 4 ];
        formData[ 0 ] = new NVPair( "userid", username );
        formData[ 1 ] = new NVPair( "password", password );
        formData[ 2 ] = new NVPair( "city2", "ipoh" );

        System.out.print( "Trying to Logging in......" );
        log( "Trying to Logging in......" );

        rsp  = conn.Post( POST_LOGIN_URL, formData );
        System.out.println("getEffectiveURI = " + rsp.getEffectiveURI() );
        /*while ( rsp.getInputStream().read( data ) != -1 )
        {
        	log( new String( data ) );
        }*/

        log( "Response from Server: " + rsp.getStatusCode() + " " + rsp.getReasonLine() );

        if ( rsp.getStatusCode() >= 400 )
        {
            System.out.println( "\nLogin failed.. response from server: " + rsp.getStatusCode() );
            log( "\nLogin failed.. response from server: " + rsp.getStatusCode() );
            conn = null;
        }

        log( "Done." );
        return conn;
    }

    private HTTPResponse requestWipStatusReport( HTTPConnection conn) throws Exception
    {
        byte[] data         = new byte[1024*2];
        HTTPResponse rsp    = null;

        System.out.println( "\t\nSubmitting the request for Wip Staus......" );
        log( "\tSubmitting the request for Wip Staus......" );

        //rsp = conn.Get( GET_WIP_STATUS );


        /*while ( rsp.getInputStream().read( data ) != -1 )
        {
            log(new String(data));
        }*/

        
        rsp = conn.Get( "/UnisemServlet?target=report&cmd=WIP_TOEXCEL&client="+m_customerName + "&reportid=RPT001&formatid=FMT001" );

        /*while ( rsp.getInputStream().read( data ) != -1 )
        {
            log(new String(data));
        }*/

        
        return rsp;
    }




    private void logout( HTTPConnection conn ) throws Exception
    {
        try
        {
            System.out.print( "\n Logging out... " );
            log( "\n Logging out... " );
            HTTPResponse rsp = conn.Get( LOG_OUT );
            System.out.println( "Successfully logged out from UNISEM Site" );
            log( "Successfully logged out from UNISEM Site" );

            conn = null;
            rsp = null;
        }
        catch ( Exception ignore )
        {
            System.out.println( "Exception Occuered While Logging Out From UNISEM Site" + ignore);
            throw ignore;
        }
    }

    private void log( String message )
    {
        if ( message == null ) return;

        if ( m_adaptorLogger != null )
        {
            synchronized ( m_adaptorLogger )
            {
                m_adaptorLogger.logDebug( message + LINE_SEPARATOR );
            }
        }
        else
        {
            System.out.println( message );
        }
    }
}
